from django.shortcuts import render
from rest_framework.decorators import action

from . import constants
# Create your views here.
from rest_framework import status
from rest_framework.generics import CreateAPIView, RetrieveAPIView, UpdateAPIView
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import ModelViewSet

from users.models import User, Address
from .serializers import CreateUserSerializer, UserDetailSerializer, EmailSerializer, UserAddressSerializer, \
    AddressTitleSerializer


class AddressViewSet(ModelViewSet):
    serializer_class = UserAddressSerializer
    permission_classes = [IsAuthenticated]

    def get_queryset(self):
        return self.request.user.addresses.filter(is_deleted=False)

    # 获取用户的地址列表
    def list(self, request, *args, **kwargs):
        queryset = self.get_queryset()
        serializer = self.get_serializer(queryset, many=True)
        user = self.request.user
        return Response({
            'user_id': user.id,
            'default_address_id': user.default_address_id,
            'limit': constants.USER_ADDRESS_COUNTS_LIMIT,
            'addresses': serializer.data,
        })

    # 保存用户地址数据
    def create(self, request, *args, **kwargs):
        # 重写主要是要判断用户的地址增加数量是否达到上限
        count = request.user.addresses.count()
        if count > constants.USER_ADDRESS_COUNTS_LIMIT:
            return Response({'message': '不可再新增地址'}, status=status.HTTP_400_BAD_REQUEST)
        return super().create(request, *args, **kwargs)

    # 删除地址, 进行逻辑删除修改字段并非真正的删除数据
    def destroy(self, request, *args, **kwargs):
        address = self.get_object()
        address.is_deleted = True
        address.save()
        return Response({'message': '逻辑删除成功'}, status=status.HTTP_204_NO_CONTENT)

    # 下面的方法都是除了提供的五种方法以外需要新增的方法
    # 用action的作用是来给router使用的
    @action(methods=['put'], detail=True)
    def status(self, request, pk=None, address_id=None):
        # 设置默认地址
        address = self.get_object()
        request.user.default_address = address
        request.user.save()
        return Response({'message': 'ok'}, status=status.HTTP_200_OK)

    # 起别名
    @action(methods=['put'], detail=True)
    def title(self, request, pk=None, address_id=None):
        address = self.get_object()
        serializer = AddressTitleSerializer(instance=address, data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data)


# 获取用户发送的email地址进行保存,且给用户发送链接验证邮箱的准确性
class EmailView(UpdateAPIView):
    serializer_class = EmailSerializer
    permission_classes = [IsAuthenticated]   # 设置权限，只有登陆用户可以访问

    # 保存用户邮箱
    def get_object(self, *args, **kwargs):
        return self.request.user


# 现在我们已经把信息发送给用户了，检验用户发送过来的token是否有效
# 提供一个方法就可以了，不需要使用序列化器验证了
class VerifyEmailView(APIView):
    def get(self, request):
        token = request.query_params.get('token')
        if not token:
            return Response({'message': '参数不全'}, status=status.HTTP_400_BAD_REQUEST)
        # 通过在data中存的user_id,email取出user
        # 静态方法，可以使用类来获取 , 返回值是user对象
        user = User.check_verify_email_token(token)
        if user is None:
            return Response({'message': '无效的token'}, status=status.HTTP_400_BAD_REQUEST)
        # 给user对象的email_active属性设置为True
        user.email_active = True
        user.save()   # 保存
        return Response({'message': 'ok'}, status=status.HTTP_200_OK)


# 获取单个用户的用户详情页
class UserDetailView(RetrieveAPIView):
    serializer_class = UserDetailSerializer
    permission_classes = [IsAuthenticated]   # 这个是确认用户是登录用户

    # 获取单一用户默认是从查询路径中找pk的，找不到会报４０４的错，但是这里的路径中并没有拼接
    # 默认只能获取登陆的唯一用户的详情信息
    def get_object(self):
        return self.request.user


class UsernameCountView(APIView):
    """
    用户名数量  # class /authorizations/
    """
    def get(self, request, username):
        """
        获取指定用户名数量
        """
        count = User.objects.filter(username=username).count()

        data = {
            'username': username,
            'count': count
        }

        return Response(data)


class MobileCountView(APIView):
    """
    手机号数量
    """
    def get(self, request, mobile):
        """
        获取指定手机号数量
        """
        count = User.objects.filter(mobile=mobile).count()

        data = {
            'mobile': mobile,
            'count': count
        }

        return Response(data)


class UserView(CreateAPIView):
    """
    用户注册
    """
    serializer_class = CreateUserSerializer
